package main

import (

    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "golang.org/x/net/context"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials/insecure"
    "log"
    "net/http"

    pb "example.com/http-grpc-server/proto/hello_http"
)

/**
* @Description: grpc服务端提供http服务
* @Author: liangan
* @Date: 2023-09-02_11:05
*/
func main() {
    // 1. 定义一个context
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    // grpc服务地址
    endpoint := "127.0.0.1:50053"
    mux := runtime.NewServeMux()
    opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}

    // HTTP转grpc
    err := pb.RegisterHelloHTTPHandlerFromEndpoint(ctx, mux, endpoint, opts)
    if err != nil {
        log.Printf("Register handler err:%v\n", err)
    }

    // 启动http并监听
    log.Printf("HTTP Listen on 8080")
    http.ListenAndServe(":8080", mux)
}

